package com.ylt.controller;



import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.utils.redis.RedisUtil;
import com.utils.ylt.MapperUtil;
import com.ylt.dao.mysqldb.ShopChatDao;
import com.ylt.dao.oracledb.WeChatDao;
import com.ylt.entity.XcxEzqCart;
import com.ylt.entity.YLT_ORDER_HEADER;
import com.ylt.service.ShopChatService;
import com.ylt.service.YltCustContactService;
import com.ylt.service.YltOrderHeaderService;
import com.ylt.service.YltOrderLineService;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


/**
 * @author zhouliang
 * @create 2018-12-03 18:07
 * 小程序接口
 */
@Controller
@RequestMapping( "/ylt")
@Api(tags = "购物车相关接口")
public class ShopChatController {

    @Autowired
    private ShopChatService shopChatService;

    @Autowired
    private YltOrderHeaderService yltOrderHeaderService;

    @Autowired
    private YltOrderLineService yltOrderLineService;

    @Autowired
    private YltCustContactService yltCustContactService;
    
    @Autowired
    WeChatDao weChatDao;
    
    @Autowired
    ShopChatDao shopChatDao;

    @Autowired
    private RedisUtil redisUtil;

    InternalLogger log = Log4JLoggerFactory.getInstance(ShopChatController.class);

    /**
     * 取购物车信息
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getShopchat",method= RequestMethod.POST)
    @ApiOperation("获取购物车信息")
    public Object getShopchat(@RequestBody XcxEzqCart xcxEzqCart) {
        Map<String,Object> returnMap = new HashMap<>();
       // Map reqMap = JSON.toJavaObject(xcxEzqCart,Map.class);
        try {
//            xcxEzqCart.setCpdm(userInfo);
            List<XcxEzqCart> imageInfo= shopChatService.selectXCX_EZQ_CART(xcxEzqCart);
            returnMap.put("data", imageInfo);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code","201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    private String getUid(){
        return "666";
    }
    @ResponseBody
    @RequestMapping(value="/getShopchatByPage",method= RequestMethod.POST)
    @ApiOperation("获取购物车信息")
    public Object getShopchatByPage(@ApiParam(value = "购物车查询参数", required = false) @RequestBody XcxEzqCart xcxEzqCart,
                                    @RequestParam(name = "pageNum",required =true ) Integer pageNum,
                                    @RequestParam(name = "pageSize",required = true) Integer pageSize) {
        Map<String,Object> returnMap = new HashMap<>();
        // Map reqMap = JSON.toJavaObject(xcxEzqCart,Map.class);
        try {
            if (pageNum==null || pageSize==null) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "无分页信息");
                returnMap.put("code","201");
                return  returnMap;
            }

            PageInfo<Map<String,Object>> imageInfo= shopChatService.selectXCX_EZQ_CARTByPage(xcxEzqCart,pageNum,pageSize);
            returnMap.put("data", imageInfo);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code","201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    /**
     *
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getChatByPage",method= RequestMethod.POST)
    @ApiOperation("获取购物车信息")
    public Object selectCartByPage(@ApiParam(value = "购物车查询参数", required = true) @RequestBody Map<String,Object> params) {
        Map<String,Object> returnMap = new HashMap<>();
        // Map reqMap = JSON.toJavaObject(xcxEzqCart,Map.class);
        Integer pageNum = params.get("pageNum")==null?1:Integer.valueOf(params.get("pageNum")+"");
        Integer pageSize = params.get("pageSize")==null?10:Integer.valueOf(params.get("pageSize")+"");
        try {
            XcxEzqCart xcxEzqCart = JSON.parseObject(JSONObject.toJSONString(params.get("cart")), XcxEzqCart.class);
            if(xcxEzqCart==null){
                returnMap.put("state", "fail");
                returnMap.put("code","201");
                returnMap.put("msg", "无参数信息");
                return  returnMap;
            }
            PageInfo<Map<String,Object>> imageInfo= shopChatService.selectXCX_EZQ_CARTByPage(xcxEzqCart,pageNum,pageSize);
            returnMap.put("data", imageInfo);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code","201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    @RequestMapping(value="/putShopchat",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation("放入获取购物车信息")
    public Object putShopchat(@RequestParam Map<String,Object> reqMap) {
        Map returnMap = new HashMap();
        try {
            int imageInfo= shopChatService.putXCX_EZQ_CART(reqMap);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    /**
     * 加入购物车，合并商品编号相同的记录
     * @param xcxEzqCart
     * @return
     */
    @RequestMapping(value="/insertShopchat",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation("放入获取购物车信息")
    public Object insertSelective(@ApiParam(value = "购物车参数", required = true) @Valid @RequestBody XcxEzqCart xcxEzqCart) {
        Map returnMap = new HashMap();
        try {
        	//{"ezqUId":"ezqUId","contact_id":"contact_id",""}
            MapperUtil mapperUtil = new MapperUtil();
            if(xcxEzqCart.getDt_item_ch_price()==null||xcxEzqCart.getContact_id()==null) {
            	returnMap.put("state", "fail");
                returnMap.put("msg", "参数操作失败");
                returnMap.put("code","201");
                return returnMap;
            }

            Float unitPrice = xcxEzqCart.getItemPrice()==null?0:Float.valueOf(xcxEzqCart.getItemPrice()+"");
            final Float orderQty = xcxEzqCart.getOrderQty()==null?0:Float.valueOf(xcxEzqCart.getOrderQty()+"");
            xcxEzqCart.setLineJe(new BigDecimal(unitPrice*orderQty));
            Map<String,Object> param = new HashMap<>();

            param.put("ezqUId",xcxEzqCart.getEzqUId());
            List<XcxEzqCart> xcxs = shopChatService.selectExistsItem(param);

            if(xcxs!=null&xcxs.size()>0){
                param.put("itemCode",xcxEzqCart.getItemCode());
                param.put("ezqUId",xcxEzqCart.getEzqUId());
                List<XcxEzqCart> xcxEzqCarts = shopChatService.selectExistsItem(param);
                if(xcxEzqCarts!=null&xcxEzqCarts.size()>0){
                    xcxEzqCarts.forEach((ezqCart)->{
                        float orderQty2 = ezqCart.getOrderQty()==null?0:Float.valueOf(ezqCart.getOrderQty()+"");
                        //orderQty2 = orderQty+orderQty2;
                        if(orderQty2!=0) {
                            ezqCart.setLineJe(new BigDecimal(unitPrice * orderQty2));
                            ezqCart.setOrderQty(new BigDecimal(orderQty2));
                            shopChatService.updateByPrimaryKeySelective(ezqCart);
                        }
                    });
                }else {
                    xcxEzqCart.setOrderNumber(xcxs.get(0).getOrderNumber());  //赋值订单编号
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    xcxEzqCart.setCjsj(new Date());
                    int imageInfo = shopChatService.insert(xcxEzqCart);
                }
            }else{
                if(xcxEzqCart.getOrderNumber()==null) {
                    //hutool工具类雪花算法生成唯一键值
                    Snowflake snowflake = IdUtil.createSnowflake(1, 1);
                    String nextIdStr = snowflake.nextIdStr();

//            XcxEzqCart xcxEzqCart = (XcxEzqCart) mapperUtil.mapperObj(reqMap, XcxEzqCart.class);
                    xcxEzqCart.setOrderNumber(nextIdStr);  //赋值订单编号
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                xcxEzqCart.setCjsj(new Date());
                Map reqMap=new HashMap();
                reqMap.put("contact_id", xcxEzqCart.getContact_id());
                reqMap.put("dt_item_ch_price", xcxEzqCart.getDt_item_ch_price());
                List tmpList=weChatDao.selectItem4InsertCart(reqMap);
                if(tmpList.size()>0) {
                	Map tmpMap=(Map)tmpList.get(0);
                	xcxEzqCart.setItemCode((String)tmpMap.get("ITEM_CODE"));
                	xcxEzqCart.setCustName((String)tmpMap.get("CUST_NAME"));
                	xcxEzqCart.setSpmc((String)tmpMap.get("T_ITEM_NAME"));
                	xcxEzqCart.setSpgg((String)tmpMap.get("T_SPEC"));
                	xcxEzqCart.setSpcs((String)tmpMap.get("T_FACTORY"));
                	xcxEzqCart.setDw((String)tmpMap.get("BZDW"));
                	xcxEzqCart.setLxdh((String)tmpMap.get("CONTACT_PHONE"));
                	xcxEzqCart.setShdz((String)tmpMap.get("CONTACT_ADDRESS"));
                	xcxEzqCart.setDlcgUId((String)tmpMap.get("U_ID"));
                	xcxEzqCart.setTarItemCode((String)tmpMap.get("TAR_ITEM_CODE"));
                	xcxEzqCart.setJx((String)tmpMap.get("JX"));
                	xcxEzqCart.setPriceListId((String)tmpMap.get("PRICE_LIST"));
                	xcxEzqCart.setCustId((String)tmpMap.get("CUST_ID"));
                	xcxEzqCart.setDtId((String)tmpMap.get("DT_ID"));
                	xcxEzqCart.setTPack(BigDecimal.valueOf(Long.valueOf((String)tmpMap.get("T_PACK"))));
                }
                int imageInfo = shopChatService.insert(xcxEzqCart);
            }
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code","201");
            log.debug(e);
        }
        return returnMap;
    }
    /**
     * 删除购物车记录
     * @param xcxEzqCart
     * @return
     */
    @RequestMapping(value="/delShopchat",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation("删除购物车记录")
    public Object delSelective(@RequestBody XcxEzqCart xcxEzqCart) {
        Map returnMap = new HashMap();
        try {
            if(xcxEzqCart==null){
                returnMap.put("state", "fail");
                returnMap.put("msg", "请选择购物车的商品后再删除");
                returnMap.put("code","201");
                return  returnMap;
            }
            if(xcxEzqCart.getLineId()==null&&xcxEzqCart.getEzqUId()==null){
                returnMap.put("state", "fail");
                returnMap.put("msg", "请选择购物车的商品后再删除");
                returnMap.put("code","201");
                return  returnMap;
            }
            if(xcxEzqCart.getLineId()!=null){
            	int imageInfo= shopChatService.deleteByPrimaryKey(xcxEzqCart.getLineId());
            }else if(xcxEzqCart.getEzqUId()!=null){
            	shopChatDao.deleteByT_U_ID(xcxEzqCart.getEzqUId());
            }
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code","201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    @RequestMapping(value="/clearShopchat",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation("清空购物车记录")
    public Object clearShopchat(@RequestBody XcxEzqCart xcxEzqCart) {
        Map returnMap = new HashMap();
        try {
            if(xcxEzqCart==null){
                returnMap.put("state", "fail");
                returnMap.put("msg", "请选择购物车的商品后再删除");
                returnMap.put("code","201");
                return  returnMap;
            }
            if(xcxEzqCart.getDlcgUId()==null&&xcxEzqCart.getEzqUId()==null){
                returnMap.put("state", "fail");
                returnMap.put("msg", "参数有误，无法清空购物车");
                returnMap.put("code","201");
                return  returnMap;
            }
            int imageInfo= shopChatService.clearCart(xcxEzqCart);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code","201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    @RequestMapping(value="/updateCart",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation("更新购物车记录")
    public Object updateCart(@RequestBody Map<String,Object> params) {
        Map returnMap = new HashMap();
        try {
            if (params == null) {
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "无参数信息");
                return returnMap;
            }
            if(params.get("lineId")==null){
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "请选中购物车的商品再修改数量");
                return returnMap;
            }
            if(params.get("orderQty")==null){
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "请填写购买数量");
                return returnMap;
            }
            String regex="^[+-]?\\d+(\\.\\d+)?$";
            if(!(params.get("orderQty")+"").matches(regex)) {
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "请填写正确的购买数量");
                return returnMap;
            }
            float orderQty = params.get("orderQty")==null?0:Float.valueOf(params.get("orderQty")+"");
            params.put("orderQty",new BigDecimal(orderQty));
            MapperUtil mapperUtil = new MapperUtil();
            XcxEzqCart xcxEzqCart = (XcxEzqCart) mapperUtil.mapperObj(params, XcxEzqCart.class);
            int imageInfo= shopChatService.updateByPrimaryKeySelective(xcxEzqCart);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code", "201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    @RequestMapping(value="/updateCartQty",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation("更新购物车记录")
    public Object updateCartQty(@RequestBody Map<String,Object> params) {
        Map returnMap = new HashMap();
        try {
            if (params == null) {
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "无参数信息");
                return returnMap;
            }
            if(params.get("lineId")==null){
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "请选中购物车的商品再修改数量");
                return returnMap;
            }

            float orderQty = params.get("orderQty")==null?0:Float.valueOf(params.get("orderQty")+"");
            params.put("orderQty",orderQty);
            int imageInfo= shopChatService.updateByOrderQty(params);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code", "201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    @RequestMapping(value="/getCartStatus",method= RequestMethod.POST)
    @ResponseBody
    @ApiOperation("获取购物车选中状态")
    public Object getCartStatus(@ApiParam(value = "购物车状态参数", required = true) @RequestBody Map<String,Object> params) {
        Map returnMap = new HashMap();
        try {
            if (params == null) {
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "无参数信息");
                return returnMap;
            }
           if(redisUtil.hExists("cart:" + getUid(), "cartstatus")){
               Object cartstatus = redisUtil.hGet("cart:" + getUid(), "cartstatus");
               returnMap.put("data", JSONArray.parseArray(cartstatus+""));
               returnMap.put("state", "success");
               returnMap.put("msg", "操作成功");
               returnMap.put("code","200");
           }else {
               redisUtil.hPut("cart:" + getUid(), "cartstatus", "[" +
                       "{" +
                       "\"itemCode\":\"1234\"," +
                       "\"status\":\"1\"" +
                       "}," +
                       "{" +
                       "\"itemCode\":\"1234\"," +
                       "\"status\":\"1\"" +
                       "}" +
                       "]");
           }
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code", "201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    private  int compare_date(String DATE1) {
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(date);
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(time);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            log.debug(exception.getMessage(), exception);
        }
        return 0;
    }

    private String valItem(Map map, String fl_name) {
        String res = "";
        String RQ_ZQX2 = map.get("RQ_ZQX2") == null ? "" : map.get("RQ_ZQX2").toString();
        String RQ_ZQX3 = map.get("RQ_ZQX3") == null ? "" : map.get("RQ_ZQX3").toString();
        String RQ_ZMHJ = map.get("RQ_ZMHJ") == null ? "" : map.get("RQ_ZMHJ").toString();
        String RQ_ZKDY = map.get("RQ_ZKDY") == null ? "" : map.get("RQ_ZKDY").toString();
        String RQ_ZDBTH = map.get("RQ_ZDBTH") == null ? "" : map.get("RQ_ZDBTH").toString();
        String RQ_ZJS = map.get("RQ_ZJS") == null ? "" : map.get("RQ_ZJS").toString();
        if ("".equals(RQ_ZQX2) && "".equals(RQ_ZQX3) && "".equals(RQ_ZMHJ) && "".equals(RQ_ZKDY) && "".equals(RQ_ZDBTH) && "".equals(RQ_ZJS)) {
            return res;
        } else {
            if ("器械二类".equals(fl_name) && this.compare_date(RQ_ZQX2) == -1) {
                res = "该单位器械二类证照过期！";
            } else if ("器械三类".equals(fl_name) && this.compare_date(RQ_ZQX3) == -1) {
                res = "该单位器械三类证照过期！";
            } else if ("麻黄碱".equals(fl_name) && this.compare_date(RQ_ZMHJ) == -1) {
                res = "该单位麻黄碱证照过期！";
            } else if ("可待因".equals(fl_name) && this.compare_date(RQ_ZKDY) == -1) {
                res = "该单位可待因证照过期！";
            } else if ("蛋白同化制剂".equals(fl_name) && this.compare_date(RQ_ZDBTH) == -1) {
                res = "该单位蛋白同化证照过期！";
            } else if ("二类精神药品".equals(fl_name) && this.compare_date(RQ_ZJS) == -1) {
                res = "该单位精神药品证照过期！";
            }
        }
        return res;
    }

    @PostMapping("/genOrder")
    @ResponseBody
    @ApiOperation("购物车生成订单")
    public Object genOrder(@RequestBody String  body){
        Map returnMap = new HashMap();
        try {
        	
            /*if (params == null) {
                returnMap.put("state", "fail");
                returnMap.put("code", "201");
                returnMap.put("msg", "无参数信息");
                return returnMap;
            }*/
//            JSONArray data = JSONArray.parseArray(params.get("data")+"");
//            List<Map> data = JSONObject.parseArray(params.get("data")+"", Map.class);
//            List<String> data =Arrays.asList((params.get("data")+"").split(""));
            //List<Map<String,String>> data = (List)params.get("data");
            JSONArray data = JSONArray.parseArray(body);
            String[] lineIdArr = new String[data.size()];
            log.debug("=============="+body);
            //[{"lineId":70}]
            String resZzxx="";
            int[] i = {0};
            for(int j=0;j<data.size();j++){
            	JSONObject jsonobj=data.getJSONObject(j);
//                String line_id = ((JSONObject)jsonobj).getString("lineId");
                String line_id = ((JSONObject)jsonobj).getString("lineId");
                lineIdArr[i[0]]=line_id;
                i[0]++;
                //取得当前购物车信息
//                XcxEzqCart xcxEzqCart = shopChatService.selectByPrimaryKey(Integer.valueOf(line_id));
            };
            if (data.size()>0){
                Map<String,Object> param = new HashMap<>();
                param.put("lineIdArr",lineIdArr);
                List<XcxEzqCart> xcxEzqCarts = shopChatService.selectExistsItem(param);
                if(xcxEzqCarts.size()==0) {
                	returnMap.put("state", "fail");
                    returnMap.put("code", "201");
                    returnMap.put("msg", "参数错误");
                    return returnMap;
                }
                //拦截佣金
                // TODO Auto-generated 拦截佣金
                //拦截店铺最小下单金额
                // TODO Auto-generated 拦截店铺最小下单金额

                Map<String,Object> paramMap = new HashMap<>();
                Map<String,Object> userMap = new HashMap<>();
                
                //Map<String,Object> params=null;
                if(xcxEzqCarts!=null&&xcxEzqCarts.size()>0){
                	XcxEzqCart xcxEzqCart = xcxEzqCarts.get(0);
	                paramMap.put("CONTACT_ID", xcxEzqCart.getContact_id());
	                paramMap.put("USERID", xcxEzqCart.getDlcgUId());
                }else {
                	returnMap.put("state", "fail");
                    returnMap.put("code", "201");
                    returnMap.put("msg", "地址错误");
                    return returnMap;
                }
                List<Map<String,Object>> addressList = yltCustContactService.selectAddress(paramMap);
                if(addressList!=null&&addressList.size()>0){
                    Map addrMap= (Map)addressList.get(0);
                    userMap.put("DT_ID", addrMap.get("SHOP_CUST_ID"));
                    userMap.put("CUST_ID", addrMap.get("CUST_ID"));
                    userMap.put("U_ID",addrMap.get("U_ID"));
                    userMap.put("ORDER_TYPE", addrMap.get("ORDER_TYPE")==null?"4":addrMap.get("ORDER_TYPE"));
                    userMap.put("SO_TYPE", addrMap.get("ORDER_TYPE")==null?"4":addrMap.get("ORDER_TYPE"));
                    userMap.put("GET_ITEM_WAY", addrMap.get("GET_ITEM_WAY")==null?"PS":addrMap.get("GET_ITEM_WAY"));
                    // 提货（配送）方式
                    if (addrMap.get("PSFS")!=null && !"".equals(addrMap.get("PSFS"))) {
                        userMap.put("TH_METHOD",addrMap.get("PSFS").toString());
                    } else {
                        userMap.put("TH_METHOD", addrMap.get("GET_ITEM_WAY")==null?"PS":addrMap.get("GET_ITEM_WAY"));
                    }
                    userMap.put("PAYMENT_TERM", addrMap.get("PAYMENT_TERM")==null?"XJXS":addrMap.get("PAYMENT_TERM"));
                    userMap.put("TERM_NAME", addrMap.get("PAYMENT_TERM")==null?"XJXS":addrMap.get("PAYMENT_TERM"));
                    userMap.put("PRICE_LIST", addrMap.get("PRICE_LIST")==null?"PS":addrMap.get("PRICE_LIST"));
                    userMap.put("YP_TAX_CODE", "WX");
                    userMap.put("SHIP_TO", addrMap.get("CONTACT_ADDRESS"));
                    userMap.put("BILL_TO", addrMap.get("CONTACT_ADDRESS"));
                    userMap.put("TG_FLAG", "否");
                    userMap.put("YFKBZ", "N");
                    userMap.put("U_NAME", addrMap.get("CONTACT_NAME")==null?addrMap.get("U_NAME"):addrMap.get("CONTACT_NAME"));
                    userMap.put("SALES_REP", addrMap.get("CONTACT_NAME")==null?addrMap.get("U_NAME"):addrMap.get("CONTACT_NAME"));
                    userMap.put("MRHW", addrMap.get("MRHW"));
                    userMap.put("CUST_NUMBER", addrMap.get("CUST_NUMBER"));
                    userMap.put("CUST_NAME", addrMap.get("CUST_NAME"));
                    userMap.put("DDHTJFS", "0");  //订单提交方式
                    userMap.put("SFXSPH", "Y");   //显示批号

//                    userMap.put("sxjShzt","N");
//                    userMap.put("sgShzt","N");
                    userMap.put("ORDER_SOURCE","2");
                    userMap.put("OH_WAREHOUSE","");
                    userMap.put("RETURN_REASON","");
                    userMap.put("T_JX_FLAG","");
                    userMap.put("DF_YWY","");
                    userMap.put("JGJB","");
                    userMap.put("ZDR","");
                    userMap.put("JSFS","");
                    userMap.put("TARGET_ORDER_NUM","");
                    userMap.put("ORDER_ZE",0);
                    userMap.put("ORDER_RETURN","");
                    userMap.put("BZ","");
                    userMap.put("CHILD_ORDER_NUMBER","");
                    userMap.put("TH_ORDER_NUMBER","");
                    userMap.put("CJ_ORDER_NUMBER","");
                    userMap.put("P_QH_ORDER_NUMBER","");
                    userMap.put("ZML","");
                    userMap.put("ZJS","");
                    userMap.put("ZMLL","");
                    userMap.put("EBS_CGDH","");
                    userMap.put("TGJH_ID","");
                    userMap.put("FPLX","");
                    userMap.put("FPFKFS","");
                    userMap.put("THYY","");

//                    userMap.put("ygyshb","W");
//                    userMap.put("tjjxzt","0");

//                    List list = (List)params.get("LINES"); //订单行参数
                    //新增对批号的校验功能
//                    String IS_JYPC = addrMap.get("IS_JYPC")==null?"N":addrMap.get("IS_JYPC").toString();
//                    if("Y".equals(IS_JYPC)){
//                        String res = this.valOrderPh(list);
//                        if(!"".equals(res)){  //存在批号为空的商品
//                            cU.putValueToApp("1", "false", res, "40004");
//                            response.getWriter().println(map2Json(cU.getStore()));
//                            return Action.SUCCESS;
//                        }
//                    }
                    //校验结束
                    if(xcxEzqCarts!=null&&xcxEzqCarts.size()>0){//插入订单行
                        List<Map<String,Object>> numList = yltOrderHeaderService.selectSEQ_YLT_ORDER_HEADER(paramMap);
                        String B2B_ORDER_NUMBER = ((Map)numList.get(0)).get("B2B_ORDER_NUMBER").toString();
                        userMap.put("B2B_ORDER_NUMBER", B2B_ORDER_NUMBER);
                        userMap.put("SO_ZT", "23");   //等待审核状态
                        yltOrderHeaderService.insertOrderHeader(userMap);

                        Map relMap = new HashMap();
                        relMap.put("CUST_ID", addrMap.get("CUST_ID"));
                        relMap.put("SHOP_CUST_ID", addrMap.get("SHOP_CUST_ID"));
                        List relList =   yltOrderHeaderService.selectByShopRel(relMap);
                        if(relList!=null&&relList.size()>0){
                            relMap = (Map)relList.get(0);
                        }
                        float JE = 0;
                        float JE_ZKQ = 0;  //折扣前金额
                        float ORDER_ZE = 0;
                        float ORDER_ZE_ZKQ = 0;
                        float UNIT_PRICE = 0;
                        float ITEM_CD_PRICE = 0; //折扣前单价
                        float ORDER_QTY = 0;
                        float ORDER_ZSE = 00;
                        float ZDSJ=00;
                        float ZJS = 0;
                        float ZML = 0;

                        for(int k=0;k<xcxEzqCarts.size();k++){  //循环行
                            Map<String,Object> lineMap = new HashMap<>();
                            XcxEzqCart xcxEzqCart = xcxEzqCarts.get(k);
                            String valIte = "";

					  /*ITEM_CODE--1468912449329319,
					  TYM--阿莫西林胶囊,
					  ORDER_QTY--0,
					  FL_NAME--化学药制剂,*/

                            lineMap.put("B2B_ORDER_NUMBER", B2B_ORDER_NUMBER);
                            lineMap.put("UNIT_PRICE", xcxEzqCart.getItemPrice());
                            lineMap.put("ORDER_QTY",xcxEzqCart.getOrderQty());
                            lineMap.put("XYL", 0);
                            lineMap.put("XQ", xcxEzqCart.getSxrq());
                            lineMap.put("ITEM_CODE",xcxEzqCart.getItemCode());

                            if(lineMap.get("FL_NAME")!=null){//过滤对商品资质校验
                                valIte = this.valItem(relMap, lineMap.get("FL_NAME").toString());
                                if(!"".equals(valIte)){
                                    resZzxx += lineMap.get("TYM") + valIte +",";
                                }
                            }
                            //新增对德尔康医药的新增字段插入
                            Map cxMap = new HashMap();
                            cxMap.put("SHOP_CUST_ID", addrMap.get("SHOP_CUST_ID"));
                            //cxMap.put("MRHW", params.get("MRHW"));
                            cxMap.put("ITEM_CODE", lineMap.get("ITEM_CODE"));
                            cxMap.put("SHOWZERO", "1");

                            String MRHW = addrMap.get("HUOZ")==null?"":addrMap.get("HUOZ").toString();
                            if(MRHW.indexOf(":")>-1){
                                if(!"".equals(MRHW)){
                                    String resArr[]=MRHW.split(":");
                                    cxMap.put("MRHWS", resArr);
                                }
                            }else{
                                cxMap.put("MRHW", addrMap.get("MRHW"));
                            }

                            //2018/10/17日 更新 处理天久康Batch_id 问题,暂时写死，APP 前台没有传递 batch_id,pc 两个字段，天久康传递的是batch_id,其它是pc
                            if("54140".equals(addrMap.get("SHOP_CUST_ID").toString())){
                                if(lineMap.get("LOTS2")!=null&&!"".equals(lineMap.get("LOTS2").toString())){
                                    if(lineMap.get("LOTS2").toString().indexOf("&%")<0){
                                        cxMap.put("BATCH_ID", lineMap.get("LOTS2"));
                                        lineMap.put("BATCH_ID", lineMap.get("LOTS2"));
                                    }
                                }
                            }else{
                                cxMap.put("ITEM_PH", lineMap.get("LOTS2"));
                                lineMap.put("ITEM_PH", lineMap.get("LOTS2"));
                            }

                            lineMap.put("HW",xcxEzqCart.getHw());
                            lineMap.put("SCRQ",xcxEzqCart.getSxrq());
                            lineMap.put("MRHW",xcxEzqCart.getHuoz());

//                            List phList = BaseBean.fetchList(cxMap, "t_usersService", "t_usersDAO", "t_users.selectItemPHXQ");
//                            if(phList!=null && phList.size()>0){
//                                Map phMap = (Map)phList.get(0);
//                                lineMap.put("HW", phMap.get("HW"));
//                                lineMap.put("HWBS", phMap.get("HWBS"));
//                                lineMap.put("SCRQ", phMap.get("SCRQ"));
//                                if("5470".equals(params.get("SHOP_CUST_ID").toString())){
//                                    lineMap.put("HUOZ", params.get("HUOZ"));
//                                }else{
//                                    if(phMap.get("HW_ID")!=null){
//                                        lineMap.put("HUOZ", phMap.get("HW_ID"));
//                                    }else{
//                                        lineMap.put("HUOZ", params.get("HUOZ"));
//                                    }
//                                }
//                                //判断天久康店铺插入批号
//                                if("54140".equals(params.get("SHOP_CUST_ID").toString())&&lineMap.get("LOTS2")!=null){
//                                    lineMap.put("ITEM_PH", phMap.get("PC"));
//                                }
//                            }else{
//                                lineMap.put("HUOZ", params.get("MRHW"));
//                            }
                            try{
                                UNIT_PRICE = xcxEzqCart.getItemPrice()==null?0:Float.valueOf(xcxEzqCart.getItemPrice().toString());
                                ORDER_QTY = xcxEzqCart.getOrderQty()==null?0:Float.valueOf(xcxEzqCart.getOrderQty().toString());
                                ITEM_CD_PRICE = UNIT_PRICE;
                                JE = UNIT_PRICE*ORDER_QTY;
                                JE_ZKQ = ITEM_CD_PRICE*ORDER_QTY;
                                lineMap.put("JE", JE);
                                lineMap.put("JE_ZKQ", JE_ZKQ);
                            }catch(Exception e){
                                lineMap.put("JE", 0.00);
                                lineMap.put("JE_ZKQ", 0.00);
                            }

                            //加入对商品下单数量的限制
                            if(ORDER_QTY==0){
                                continue;
                            }
                            //加入对底价是否重新计算的判断
                            if(lineMap.get("LIMITPRICE")!=null){
                                lineMap.put("ZDSJ", lineMap.get("LIMITPRICE"));
                            }else{
                                Map djMap = new HashMap();
                                djMap.put("CUST_ID", addrMap.get("CUST_ID"));
                                djMap.put("DT_ID", addrMap.get("SHOP_CUST_ID"));
                                djMap.put("ITEM_CODE", lineMap.get("ITEM_CODE"));
                                djMap.put("SALES_CHANNEL", xcxEzqCart.getPriceListId());
                                List djList = yltOrderHeaderService.F_GETDJForLine(djMap);

                                if(djList!=null && djList.size()>0){
                                    Map map = (Map)djList.get(0);
                                    lineMap.put("ZDSJ", map.get("XSDJ")==null?"":map.get("XSDJ").toString());
                                }
                            }
                            Map djMap = new HashMap();
                            djMap.put("CUST_ID", addrMap.get("CUST_ID"));
                            djMap.put("DT_ID", addrMap.get("SHOP_CUST_ID"));
                            djMap.put("ITEM_CODE", lineMap.get("ITEM_CODE"));
                            djMap.put("SALES_CHANNEL", xcxEzqCart.getPriceListId());
                            List lpList =  yltOrderHeaderService.F_GETDJForLine(djMap);
                            if(lpList!=null && lpList.size()>0){
                                Map itemPrice = (Map)lpList.get(0);
                                lineMap.put("ITEM_LIMIT_PRICE", itemPrice.get("ITEM_LIMIT_PRICE"));
                                lineMap.put("XSZDJ", itemPrice.get("ITEM_PRICE"));
                            }
                            ZDSJ=Float.parseFloat(lineMap.get("ZDSJ")==null?"0":lineMap.get("ZDSJ").toString());
                            float ITEM_LIMIT_PRICE=Float.parseFloat(lineMap.get("ITEM_LIMIT_PRICE")==null?"0":lineMap.get("ITEM_LIMIT_PRICE").toString());
                            if(ZDSJ<ITEM_LIMIT_PRICE){
                                ZDSJ=ITEM_LIMIT_PRICE;
                            }

                            ///加入购物车
                            if("".equals(valIte)){
                                List itemList =  yltOrderHeaderService.getSPJCXX(djMap);
                                if (itemList==null || itemList.size()==0) {
                                    continue;
                                }
                                Map itemMap =(Map)itemList.get(0);
                                //计算毛利率，件数
                                String T_MEASURE_SPEC = itemMap.get("OLD_T_MEASURE_SPEC")==null?"0":itemMap.get("OLD_T_MEASURE_SPEC").toString();
                                float JS = 0;
                                float ML = 0;
                                UNIT_PRICE = Float.parseFloat(lineMap.get("UNIT_PRICE")==null?"0":lineMap.get("UNIT_PRICE").toString());
                                ORDER_QTY = Float.parseFloat(lineMap.get("ORDER_QTY")==null?"0":lineMap.get("ORDER_QTY").toString());
                                ZDSJ = Float.parseFloat(lineMap.get("ZDSJ")==null?"0":lineMap.get("ZDSJ").toString());
                                if(!"0".equals(T_MEASURE_SPEC)){
                                    JS = ORDER_QTY/Float.parseFloat(T_MEASURE_SPEC);
                                }
                                ML = (UNIT_PRICE-ZDSJ)*ORDER_QTY;
                                lineMap.put("JS", JS);
                                lineMap.put("ML", ML);
                                ZJS = ZJS+JS;
                                ZML = ZML+ML;
                                lineMap.putAll(itemMap);

                                yltOrderLineService.insertOrderLine(lineMap);
                                shopChatService.deleteByPrimaryKey(xcxEzqCart.getLineId());
                            }
                        }
                        Map zjeMap = new HashMap();
                        YLT_ORDER_HEADER yltOrderHeader=new YLT_ORDER_HEADER();
                        zjeMap.put("B2B_ORDER_NUMBER", B2B_ORDER_NUMBER);
                        List listZje = yltOrderHeaderService.selectZje(zjeMap);
                        if(listZje!=null && listZje.size()>0){
                            ORDER_ZE = Float.parseFloat(((Map)listZje.get(0)).get("ORDER_ZE").toString());
                            ORDER_ZE_ZKQ  = Float.parseFloat(((Map)listZje.get(0)).get("ORDER_ZE_ZKQ").toString());
                            if(ORDER_ZE!=0){
                                yltOrderHeader.setOrderZe(new BigDecimal(ORDER_ZE));
                                yltOrderHeader.setOrderGxsj(new Date());
                                yltOrderHeader.setZjs(new BigDecimal(ZJS));
                                yltOrderHeader.setZml(new BigDecimal(ZML));
                                yltOrderHeader.setB2bOrderNumber(B2B_ORDER_NUMBER);
                                zjeMap.put("ORDER_ZE", ORDER_ZE);
                                zjeMap.put("ORDER_GXSJ", ORDER_ZE);
                                zjeMap.put("ZJS", ZJS);
                                zjeMap.put("ZML", ZML);
                                yltOrderHeaderService.updateByPrimaryKeySelective(yltOrderHeader);
                            }
                        }
                        yltOrderHeaderService.updateGWC(zjeMap);
                        if(!"".equals(resZzxx)){
                            returnMap.put("state", "fail");
                            returnMap.put("code", "40003");
                            returnMap.put("msg", resZzxx);
                        }
//                        else{
//                            // 发送订单信息到微信
//                            Map wxMap = new HashMap();
//                            // 选择模板id用
//                            wxMap.put("TEMPLATE_TYPE", "23");
//                            wxMap.put("U_ID", params.get("USERID").toString());
//                            wxMap.put("U_NAME", params.get("U_NAME").toString());
//                            wxMap.put("SHOP_CUST_ID", params.get("SHOP_CUST_ID").toString());
//                            wxMap.put("B2B_ORDER_NUMBER", B2B_ORDER_NUMBER);
//                            wxMap.put("ORDER_ZE", String.valueOf(ORDER_ZE));
//                            wxMap.put("BZ", params.get("BZ")==null?"":params.get("BZ").toString());
//                            SendWxMessageUtil wxMsg = new SendWxMessageUtil();
//                            wxMsg.sendWxMessage(wxMap);
//                            cU.putValueToApp("1", "true", "提交成功", "40000");
//                        }
                    }else{
                        returnMap.put("state", "fail");
                        returnMap.put("code", "40004");
                        returnMap.put("msg", "请选择商品后再提交");
                        return returnMap;
                    }
                }else{
                    returnMap.put("state", "fail");
                    returnMap.put("code", "40003");
                    returnMap.put("msg", "请选择收货地址");
                    return returnMap;
                }
            }
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
            returnMap.put("code","200");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            returnMap.put("code", "201");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }
}